import mockData from './data';
import type { ResultData } from '../types/api';

/**
 * Mock 服务设置
 * 提供模拟数据服务的配置和初始化功能
 */

/**
 * 模拟网络延迟
 * @param min - 最小延迟时间（毫秒）
 * @param max - 最大延迟时间（毫秒）
 * @returns Promise
 */
const mockDelay = (min: number = 300, max: number = 1000): Promise<void> => {
  const delay = Math.random() * (max - min) + min;
  return new Promise(resolve => setTimeout(resolve, delay));
};

/**
 * 创建成功响应
 * @param data - 响应数据
 * @param message - 响应消息
 * @returns ResultData
 */
const createSuccessResponse = <T>(data: T, message: string = '操作成功'): ResultData<T> => ({
  code: 200,
  message,
  data,
  success: true,
});

/**
 * 创建错误响应
 * @param message - 错误消息
 * @param code - 错误码
 * @returns ResultData
 */
const createErrorResponse = (message: string = '操作失败', code: number = 500): ResultData => ({
  code,
  message,
  data: null,
  success: false,
});

/**
 * Mock API 路由配置
 */
export const mockRoutes = {
  // 用户相关接口
  'GET /api/users': async (params?: any) => {
    await mockDelay();
    const { current = 1, pageSize = 10 } = params || {};
    const pageData = mockData.generatePageData(mockData.users, current, pageSize);
    return createSuccessResponse(pageData, '获取用户列表成功');
  },

  'GET /api/users/:id': async (id: string) => {
    await mockDelay();
    const user = mockData.users.find(u => u.id === id);
    if (user) {
      return createSuccessResponse(user, '获取用户详情成功');
    }
    return createErrorResponse('用户不存在', 404);
  },

  'POST /api/users': async (userData: any) => {
    await mockDelay();
    const newUser = {
      id: String(Date.now()),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      ...userData,
    };
    mockData.users.push(newUser);
    return createSuccessResponse(newUser, '创建用户成功');
  },

  'PUT /api/users/:id': async (id: string, userData: any) => {
    await mockDelay();
    const userIndex = mockData.users.findIndex(u => u.id === id);
    if (userIndex !== -1) {
      mockData.users[userIndex] = {
        ...mockData.users[userIndex],
        ...userData,
        updateTime: new Date().toISOString(),
      };
      return createSuccessResponse(mockData.users[userIndex], '更新用户成功');
    }
    return createErrorResponse('用户不存在', 404);
  },

  'DELETE /api/users/:id': async (id: string) => {
    await mockDelay();
    const userIndex = mockData.users.findIndex(u => u.id === id);
    if (userIndex !== -1) {
      mockData.users.splice(userIndex, 1);
      return createSuccessResponse(true, '删除用户成功');
    }
    return createErrorResponse('用户不存在', 404);
  },

  // 任务相关接口
  'GET /api/tasks': async (params?: any) => {
    await mockDelay();
    const { current = 1, pageSize = 10 } = params || {};
    const pageData = mockData.generatePageData(mockData.tasks, current, pageSize);
    return createSuccessResponse(pageData, '获取任务列表成功');
  },

  'GET /api/tasks/:id': async (id: string) => {
    await mockDelay();
    const task = mockData.tasks.find(t => t.id === id);
    if (task) {
      return createSuccessResponse(task, '获取任务详情成功');
    }
    return createErrorResponse('任务不存在', 404);
  },

  'POST /api/tasks': async (taskData: any) => {
    await mockDelay();
    const newTask = {
      id: String(Date.now()),
      createTime: new Date().toISOString(),
      progress: 0,
      ...taskData,
    };
    mockData.tasks.push(newTask);
    return createSuccessResponse(newTask, '创建任务成功');
  },

  'PUT /api/tasks/:id': async (id: string, taskData: any) => {
    await mockDelay();
    const taskIndex = mockData.tasks.findIndex(t => t.id === id);
    if (taskIndex !== -1) {
      mockData.tasks[taskIndex] = {
        ...mockData.tasks[taskIndex],
        ...taskData,
      };
      return createSuccessResponse(mockData.tasks[taskIndex], '更新任务成功');
    }
    return createErrorResponse('任务不存在', 404);
  },

  'DELETE /api/tasks/:id': async (id: string) => {
    await mockDelay();
    const taskIndex = mockData.tasks.findIndex(t => t.id === id);
    if (taskIndex !== -1) {
      mockData.tasks.splice(taskIndex, 1);
      return createSuccessResponse(true, '删除任务成功');
    }
    return createErrorResponse('任务不存在', 404);
  },

  // 系统相关接口
  'GET /api/system/info': async () => {
    await mockDelay();
    return createSuccessResponse(mockData.systemInfo, '获取系统信息成功');
  },

  'GET /api/system/stats': async () => {
    await mockDelay();
    return createSuccessResponse(mockData.systemStats, '获取系统统计成功');
  },

  'GET /api/system/monitor': async () => {
    await mockDelay();
    return createSuccessResponse(mockData.systemMonitor, '获取系统监控成功');
  },
};

/**
 * 初始化 Mock 服务
 * 在开发环境中启用 Mock 数据
 */
export const setupMock = () => {
  if (import.meta.env.DEV) {
    console.log('🚀 Mock 服务已启动');
    console.log('📊 可用的 Mock 数据:', Object.keys(mockRoutes));
  }
};

/**
 * 获取 Mock 数据
 * @param key - 数据键名
 * @returns Mock 数据
 */
export const getMockData = (key: keyof typeof mockData) => {
  return mockData[key];
};

export default {
  setupMock,
  getMockData,
  mockRoutes,
};